package search

import (
	"appengine"
	"appengine/search"
	"entity"
)

/*
	Search News
*/

var newsIndexName string = "news_v2"
var limit int = 10

func AddNews(c appengine.Context, obj entity.NewsSearch) error {
	index, err := search.Open(newsIndexName)
	if err != nil {
		return err
	} else {
		_, err := index.Put(c, obj.Alias, &obj)
		if err != nil {
			return err
		}
	}
	return nil
}

func GetNews(c appengine.Context, id string, obj *entity.NewsSearch) error {
	index, err := search.Open(newsIndexName)
	if err != nil {
		return err
	} else {
		err := index.Get(c, id, obj)
		c.Infof(obj.Title)
		if err != nil {
			return err
		}
		return nil
	}
}

func SearchNews(c appengine.Context, query string, page int) (results []entity.NewsSearch, err error) {
	index, err := search.Open(newsIndexName)
	if err != nil {
		return results, err
	} else {

		for t := index.Search(c, query, nil); ; {
			var doc entity.NewsSearch
			_, err := t.Next(&doc)
			if err == search.Done {
				break
			} else {
				if err != nil {
					return results, err
				} else {
					results = append(results, doc)
				}
			}
		}
	}
	return results, nil
}

func DeleteNews(c appengine.Context, id string) error {
	index, err := search.Open(newsIndexName)
	if err != nil {
		return err
	} else {
		err := index.Delete(c, id)
		if err != nil {
			return err
		}
		return nil
	}
}
